<script setup>
import { ref, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from '../store/auth'

const props = defineProps({
  isCollapse: {
    type: Boolean,
    default: false
  },
  activeMenu: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['menu-select'])

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()

// 当前选中的菜单
const selectedMenu = ref('')

// 获取用户菜单
const userMenus = computed(() => authStore.menus)

// 过滤有权限的菜单
const filteredMenus = computed(() => {
  return filterMenusByPermission(userMenus.value)
})

// 根据权限过滤菜单
function filterMenusByPermission(menus) {
  return menus.filter(menu => {
    // 检查当前菜单是否有权限
    if (menu.meta && menu.meta.permissions && menu.meta.permissions.length > 0) {
      const hasPermission = menu.meta.permissions.some(permission => 
        authStore.hasPermission(permission)
      )
      if (!hasPermission) return false
    }
    
    // 如果有子菜单，递归过滤
    if (menu.children && menu.children.length > 0) {
      menu.children = filterMenusByPermission(menu.children)
      // 如果所有子菜单都没有权限，则隐藏父菜单
      return menu.children.length > 0
    }
    
    return true
  })
}

// 处理菜单点击
const handleMenuSelect = (index, indexPath) => {
  selectedMenu.value = index
  emit('menu-select', index)
  
  // 如果是可导航的菜单项，则进行路由跳转
  const menuItem = findMenuByPath(index, userMenus.value)
  if (menuItem && menuItem.path && !menuItem.children) {
    router.push(menuItem.path)
  }
}

// 根据路径查找菜单项
function findMenuByPath(path, menus) {
  for (const menu of menus) {
    if (menu.path === path) {
      return menu
    }
    if (menu.children) {
      const found = findMenuByPath(path, menu.children)
      if (found) return found
    }
  }
  return null
}

// 渲染菜单图标
const renderIcon = (icon) => {
  if (!icon) return null
  
  // 处理 Element Plus 图标
  if (icon.startsWith('el-icon-')) {
    return h('i', { class: icon })
  }
  
  // 处理其他图标
  return h('i', { class: `iconfont ${icon}` })
}

// 监听路由变化，更新选中菜单
watch(() => route.path, (newPath) => {
  selectedMenu.value = newPath
}, { immediate: true })

// 监听外部activeMenu变化
watch(() => props.activeMenu, (newActive) => {
  selectedMenu.value = newActive
})
</script>

<template>
  <div class="side-menu">
    <el-menu
      :default-active="selectedMenu"
      :collapse="isCollapse"
      :unique-opened="true"
      background-color="#ffffff"
      text-color="#6b7280"
      active-text-color="#3b82f6"
      @select="handleMenuSelect"
      class="custom-menu"
    >
      <template v-for="menu in filteredMenus" :key="menu.id">
        <!-- 有子菜单的情况 -->
        <el-sub-menu 
          v-if="menu.children && menu.children.length > 0" 
          :index="menu.path"
        >
          <template #title>
            <el-icon v-if="menu.icon">
              <component :is="menu.icon" />
            </el-icon>
            <span>{{ menu.title }}</span>
          </template>
          
          <template v-for="child in menu.children" :key="child.id">
            <!-- 子菜单还有子菜单 -->
            <el-sub-menu
              v-if="child.children && child.children.length > 0"
              :index="child.path"
            >
              <template #title>
                <el-icon v-if="child.icon">
                  <component :is="child.icon" />
                </el-icon>
                <span>{{ child.title }}</span>
              </template>
              
              <el-menu-item
                v-for="grandchild in child.children"
                :key="grandchild.id"
                :index="grandchild.path"
              >
                <el-icon v-if="grandchild.icon">
                  <component :is="grandchild.icon" />
                </el-icon>
                <span>{{ grandchild.title }}</span>
              </el-menu-item>
            </el-sub-menu>
            
            <!-- 普通子菜单项 -->
            <el-menu-item v-else :index="child.path">
              <el-icon v-if="child.icon">
                <component :is="child.icon" />
              </el-icon>
              <span>{{ child.title }}</span>
            </el-menu-item>
          </template>
        </el-sub-menu>
        
        <!-- 没有子菜单的情况 -->
        <el-menu-item v-else :index="menu.path">
          <el-icon v-if="menu.icon">
            <component :is="menu.icon" />
          </el-icon>
          <span>{{ menu.title }}</span>
        </el-menu-item>
      </template>
    </el-menu>
  </div>
</template>

<style scoped>
.side-menu {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 8px;
}

.side-menu .el-menu {
  border-right: none;
  height: 100%;
  background: transparent;
}

.side-menu .el-menu:not(.el-menu--collapse) {
  width: 244px;
}

/* 自定义滚动条样式 */
.side-menu::-webkit-scrollbar {
  width: 4px;
}

.side-menu::-webkit-scrollbar-track {
  background: transparent;
}

.side-menu::-webkit-scrollbar-thumb {
  background: #d1d5db;
  border-radius: 2px;
}

.side-menu::-webkit-scrollbar-thumb:hover {
  background: #9ca3af;
}

/* 菜单项样式调整 */
:deep(.el-menu-item),
:deep(.el-sub-menu__title) {
  height: 48px;
  line-height: 48px;
  border-radius: 8px;
  margin-bottom: 4px;
  transition: all 0.3s cubic-bezier(0.2, 0, 0, 1);
  background: transparent;
  border: none;
  position: relative;
  overflow: hidden;
}

:deep(.el-menu-item:hover),
:deep(.el-sub-menu__title:hover) {
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%) !important;
  color: #374151 !important;
  transform: translateX(8px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

:deep(.el-menu-item.is-active) {
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%) !important;
  color: #667eea !important;
  font-weight: 600;
  transform: translateX(12px);
  box-shadow: 0 6px 16px rgba(102, 126, 234, 0.15);
}

:deep(.el-sub-menu .el-menu-item) {
  background: transparent;
  margin-left: 16px;
  border-radius: 6px;
  height: 40px;
  line-height: 40px;
}

:deep(.el-sub-menu .el-menu-item:hover) {
  background: rgba(102, 126, 234, 0.05) !important;
  transform: translateX(12px);
}

:deep(.el-sub-menu .el-menu-item.is-active) {
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.15) 0%, rgba(118, 75, 162, 0.15) 100%) !important;
  color: #667eea !important;
  font-weight: 600;
  transform: translateX(16px);
}

/* 折叠状态下的样式 */
:deep(.el-menu--collapse .el-menu-item),
:deep(.el-menu--collapse .el-sub-menu > .el-sub-menu__title) {
  padding: 0 20px !important;
  justify-content: center;
}

:deep(.el-menu--collapse .el-menu-item > span),
:deep(.el-menu--collapse .el-sub-menu > .el-sub-menu__title > span) {
  display: none;
}

/* 图标样式 */
:deep(.el-icon) {
  margin-right: 8px;
  font-size: 16px;
}

:deep(.el-menu--collapse .el-icon) {
  margin-right: 0;
  font-size: 18px;
}

/* 子菜单箭头样式 */
:deep(.el-sub-menu__icon-arrow) {
  font-size: 12px;
  transition: transform 0.15s ease;
}

:deep(.el-sub-menu.is-opened > .el-sub-menu__title .el-sub-menu__icon-arrow) {
  transform: rotateZ(180deg);
}

/* 子菜单展开动画 */
:deep(.el-menu--vertical .el-menu) {
  background: transparent;
}

:deep(.el-menu--popup) {
  background: #ffffff !important;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05), 0 1px 3px rgba(0, 0, 0, 0.1);
}
</style>